import cv2
import matplotlib.pyplot as plt

def show(img, title='Image'):
    """使用 matplotlib 显示图像"""
    if isinstance(img, str):
        img = cv2.imread(img)

    if img is None:
        raise ValueError("图像为空，可能是路径错误或图像未加载成功")

    if len(img.shape) == 3:
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        plt.imshow(img)
    else:
        plt.imshow(img, cmap='gray')

    plt.title(title)
    plt.axis('off')
    plt.show()

def _tran_canny(img):
    """图像边缘提取（灰度 + 模糊 + Canny）"""
    if len(img.shape) == 3:
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    else:
        gray = img
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)
    edges = cv2.Canny(blurred, 50, 150)
    return edges

def detect_displacement(img_slider_path, img_background_path, save_path="output.png"):
    """检测滑块缺口位置并保存标记图"""
    # 读取图像
    slider = cv2.imread(img_slider_path)
    background = cv2.imread(img_background_path)

    if slider is None or background is None:
        raise ValueError("图像加载失败，请检查路径")

    # 边缘检测
    slider_edge = _tran_canny(slider)
    background_edge = _tran_canny(background)

    # 模板匹配
    res = cv2.matchTemplate(background_edge, slider_edge, cv2.TM_CCOEFF_NORMED)
    _, max_val, _, max_loc = cv2.minMaxLoc(res)

    print(f"匹配得分：{max_val:.4f}")
    print(f"缺口位置：{max_loc}")

    # 在原图中标记缺口位置
    h, w = slider_edge.shape
    top_left = max_loc
    bottom_right = (top_left[0] + w, top_left[1] + h)

    marked_image = background.copy()
    cv2.rectangle(marked_image, top_left, bottom_right, (0, 0, 255), 2)

    # 保存为新图像
    cv2.imwrite(save_path, marked_image)
    print(f"标记图已保存为：{save_path}")

    # 可选：显示图像
    show(marked_image, "标记缺口图")

    return top_left[0]  # 返回横坐标
def crop_and_save(image_path, coord1, coord2, save_path):
    """
    根据两组坐标裁剪图片并保存

    参数:
    - image_path: 原图路径 (str)
    - coord1: 第一个坐标 (x1, y1) 元组或列表
    - coord2: 第二个坐标 (x2, y2) 元组或列表
    - save_path: 裁剪后图片保存路径 (str)
    """

    # 读取图片
    img = cv2.imread(image_path)
    if img is None:
        raise ValueError("图片加载失败，请检查路径")

    x1, y1 = coord1
    x2, y2 = coord2

    # 确保坐标是左上和右下
    x_min, x_max = sorted([x1, x2])
    y_min, y_max = sorted([y1, y2])

    # 裁剪
    cropped = img[y_min:y_max, x_min:x_max]

    # 保存裁剪后的图片
    cv2.imwrite(save_path, cropped)
    print(f"裁剪图片已保存到: {save_path}")
    return  save_path
# 示例调用
if __name__ == "__main__":
    # x = detect_displacement("img2.png", "img1.png", save_path="marked_gap.png")
    # print(f"滑块应该移动到的位置 x = {x}")
    crop_and_save("img.png", (145, 495), (255, 605), "cropped.png")